package com.mnsq.subject.service.impl;

import com.mnsq.common.bean.condition.DocumentCondition;
import com.mnsq.common.bean.enums.StatusEnum;
import com.mnsq.common.service.MongoService;
import com.mnsq.common.tools.jpa.JpaExample;
import com.mnsq.common.tools.jpa.ReflectValueUtil;
import com.mnsq.common.tools.tool.BeanCopyUtils;
import com.mnsq.subject.bean.condition.SubjectCondition;
import com.mnsq.subject.bean.document.SubjectMg;
import com.mnsq.subject.bean.entity.Subject;
import com.mnsq.subject.bean.entity.SubjectContent;
import com.mnsq.subject.bean.enums.SubjectType;
import com.mnsq.subject.dao.SubjectContentRepository;
import com.mnsq.subject.dao.SubjectRepository;
import com.mnsq.subject.service.MongoDbService;
import com.mnsq.user.bean.base.ThreadLocalInfo;
import com.mnsq.user.bean.dto.LoginInfo;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Optional;

/**
 * @author 周俭
 */
@Service
public class MongoDbServiceImpl implements MongoDbService {

    @Autowired
    private MongoService<SubjectMg> mongoService;

    @Autowired
    private SubjectRepository subjectRepository;
    @Autowired
    private SubjectContentRepository subjectContentRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void agree(DocumentCondition documentCondition) {
        Subject subject = queryByUnique(MapUtils.getString(documentCondition.getQueryParams(), "unique"));
        if (subject != null) {
            if (subject.getStatus().equals(StatusEnum.SUBJECT_AGREE.value)) {
                throw new IllegalStateException("该信息已审核");
            }
            Optional<SubjectContent> sc = subjectContentRepository.findById(subject.getSubjectContentId());
            SubjectMg subjectMgMongo = new SubjectMg();
            subjectMgMongo.saveInit();
            Integer type = subject.getType();
            BeanCopyUtils.copyNullProperties(subject, subjectMgMongo);
            subjectMgMongo.setContent(sc.orElse(new SubjectContent()).getDoc());
            subjectMgMongo.setHtmlContent(sc.orElse(new SubjectContent()).getContent());
            subjectMgMongo.setSubject(subject.getSubject());
            subjectMgMongo.setHtmlSubject(subject.getSubjectHtml());
            if (SubjectType.exists(type)) {
                subjectMgMongo.setType(SubjectType.getType(type));
            } else {
                throw new IllegalArgumentException("不支持的内容类型");
            }
            // 保存作者信息
            LoginInfo loginInfo = ThreadLocalInfo.LOGIN_INFO.get();
            if (subject.getAgreed() == null || !subject.getAgreed()) {
                subjectMgMongo.setUserName(loginInfo.getPetName());
                subjectMgMongo.setUserId(loginInfo.getUserId());
                subjectMgMongo.setUserHeadPic(loginInfo.getHeadPicSmall());
                mongoService.save(subjectMgMongo);
            } else {
                documentCondition.setUpdateParams(new HashMap<String, String>() {{
                    putAll(ReflectValueUtil.objToMap(subjectMgMongo, SubjectMg.class));
                    put("userName", loginInfo.getPetName());
                    put("userHeadPic", loginInfo.getHeadPicSmall());
                    put("userId", loginInfo.getUserId() + "");
                }});
                mongoService.update(documentCondition);
            }
            subject.setAgreed(true);
            subject.setStatus(StatusEnum.SUBJECT_AGREE.value);
            subjectRepository.saveAndFlush(subject);
        }
    }

    @Override
    public void disagree(DocumentCondition documentCondition) {
        Subject subject = queryByUnique(MapUtils.getString(documentCondition.getQueryParams(), "unique"));
        if (subject != null) {
            if (subject.getStatus().equals(StatusEnum.SUBJECT_DISAGREE.value)) {
                throw new IllegalStateException("该信息已拒绝");
            }
            subject.setStatus(StatusEnum.SUBJECT_DISAGREE.value);
            subject.setReason(MapUtils.getString(documentCondition.getUpdateParams(), "reason"));
            subjectRepository.saveAndFlush(subject);
        }
    }

    private Subject queryByUnique(String unique) {
        SubjectCondition subjectCondition = new SubjectCondition();
        subjectCondition.setUnique(unique);
        subjectCondition.setStatus(null);
        Optional<Subject> one = subjectRepository.findOne(JpaExample.getInstance().getExample(subjectCondition, subjectCondition.getInstance()));
        return one.orElse(null);
    }
}
